package com.dream.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.dream.entity.ResponseResult;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtils {

    public static final String AUTH_HEADER = "Authorization";

    public static final String AUTH_HEADER_TYPE = "Bearer ";

    public static final String JWT_SIGN_KEY = "dream";

    public static final String KAPTCHA_SESSION_KEY = "kaptcha_session_key";

    public static String createToken(String username, String password) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expTime = now.plusDays(1);
        Map<String, Object> payload = new HashMap<>();
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(JWTPayload.EXPIRES_AT, expTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        // 内容
        payload.put("username", username);
        payload.put("password", password);
        return JWTUtil.createToken(payload, JWT_SIGN_KEY.getBytes(StandardCharsets.UTF_8));
    }

    public static void writeResponse(HttpServletResponse response, String token, ResponseResult responseResult) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("token", token);
        response.getWriter().println(JSONUtil.toJsonStr(responseResult));
        response.getWriter().flush();
    }
}
